﻿//************************************************************************************************************
// CoNatural.Data.dll
// Author: Roger Torres
//************************************************************************************************************
// You can use, modify, and distribute the source code and executable programs based on the source code.
// This source code is provided "as is" and without warranties as to performance or merchantability. 
// The author and/or distributors of this source code may have made statements about this source code. 
// Any such statements do not constitute warranties and shall not be relied on by the user in deciding 
// whether to use this source code. This source code is provided without any express or implied warranties 
// whatsoever. Because of the diversity of conditions and hardware under which this source code may be used, 
// no warranty of fitness for a particular purpose is offered. The user is advised to test the source code 
// thoroughly before relying on it. The user must assume the entire risk of using the source code.
//************************************************************************************************************

using System;
using System.Data;
using CoNatural.Binders;
using System.Collections.Generic;

namespace CoNatural.Data {
	/// <summary>
	/// Command execution context
	/// </summary>
	public class CommandExecutionContext : ExecutionContextBase {
		public object Target { get; private set; }

		/// <summary>
		/// Constructor for single command execution
		/// </summary>
		internal CommandExecutionContext(IConnection connection, ICommand command) : this(connection, command, null) { }

		/// <summary>
		/// Constructor for single command execution bound to an object
		/// </summary>
		internal CommandExecutionContext(IConnection connection, ICommand command, object target)
			: base(connection, command) {
			if (target != null)
				Target = target;
		}

		#region Execution

		internal int ExecuteNonQuery() {
			return DbCommand.ExecuteNonQuery();
		}

		internal T ExecuteScalar<T>() {
			return (T)DbCommand.ExecuteScalar();
		}

		#endregion Execution

		#region Bindings

		/// <summary>
		/// Model -> ICommand
		/// </summary>
		protected internal override void BindIn() {
			if(Target != null)
				Connection.DataBinder.Bind(Target, Command);
		}

		/// <summary>
		/// ICommand -> Model
		/// </summary>
		protected internal override void BindOut() {
			if(Target != null)
				Connection.DataBinder.Bind(Command, Target);
		}

		#endregion Bindings
	}
}
